<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@page import="com.opensymphony.xwork2.ognl.OgnlValueStack" %>
<%((OgnlValueStack) request.getAttribute("struts.valueStack")).set("context", request.getParameter("context"));%>

<%--<s:property value="#request.context"/>--%>
<%--${param.context}--%>

<script type="text/javascript">
    $(function () {
        var requestId = '${param.requestId}';
        var container = requestId ? $('div#tab_' + requestId) : document;


        var attachmentUpload = '${param.uploaderId}';
        var uploadBrowserId = "${param.uploadBrowserId}";
        var gridId = '${param.gridId}';
//        console.log($.jgrid.format("attachmentUpload={0}, uploadBrowserId={1}, gridId={2}", attachmentUpload, uploadBrowserId, gridId ));

//        var attachmentUpload = 'requestAttachmentUpload';
//        var uploadBrowserId = "uploadRequestAttachment";
//        var gridId = 'requestAttachmentsGrid';

        //attachment download URL
        var attachmentDownloadUrl = 'download-attachment?id=';
        var uploadAttachmentUrl = 'upload-attachment';
        <s:if test="#request.context=='viewDialog'">
        uploadAttachmentUrl = 'update-request-attachment'
        </s:if>
        var gridURL = '';


        $('#' + uploadBrowserId, container).button({
            label: '<s:text name="request.add"/>'
        }).css({
                    overflow: 'hidden'
                }).append($("<input type='file' id='" + attachmentUpload + "' name='upload' <s:if test="%{guest}">disabled</s:if> title='Please choose file' multiple/>").css({
                    position: 'absolute',
                    top: -3,
                    right: -3,
                    border: '1px solid',
                    borderWidth: '10px 180px 40px 20px',
                    opacity: 0,
                    filter: 'alpha(opacity=0)',
                    cursor: 'pointer'
                })).on('click',function () {

                }).height(23)
        <%--<s:if test="#request.context=='viewDialog'">.position({my: 'center', at: 'center', of: '#gview_commentAttachmentsGrid'})</s:if>--%>
        ;


        $('#' + attachmentUpload, container).fileupload({
            type: 'POST',
            dataType: 'json',
            url: uploadAttachmentUrl, add: function (e, data) {
                var appId;
                $.each(data.files, function (index, file) {
                    console.log("Index=", index, ", file=", file);
                });

                $(this).fileupload('option', 'formData', [
                    {
                        <s:if test="#request.context=='viewDialog'">
                        name: 'id',
                        value: $("#requestId", container).val()
                        </s:if>
                    }
                ]);
                $.blockUI();
                data.submit();
            },
            progressall: function (e, data) {
//                var progress = data.loaded / data.total * 100;
//                console.log(progress);
            },
            done: function (e, data) {
                console.log("upload down.");
                var jsonFromServer, pb;
                $.unblockUI();
                jsonFromServer = data.result;
                if (0 !== jsonFromServer.status) {
                    $.msgBox(jsonFromServer.message, null, {
                        title: 'Error',
                        height: 600,
                        width: 800
                    });
                    return;
                }
                var gridJSON = jsonFromServer.attachmentsJSON;
                console.log(gridJSON);
                console.log('grid=' + gridId);
                var attachmentsGrid = $("#" + gridId, container);
                attachmentsGrid[0].addJSONData(gridJSON);
                attachmentsGrid.setGridState('visible');

            },
            fail: function(e, data){
                $.unblockUI();
                console.dir(data);
            }
        });


        var colModel = [
            {
                name: 'name',
                index: 'name',
                align: 'left'
            },
            {
                name: 'size',
                index: 'size',
                align: 'right',
                width: 80,
                formatter: 'integer', formatoptions: {}
            }
            ,
            {
                name: 'createTime',
                index: 'createTime',
                align: 'left',
                formatter: 'date', formatoptions: {srcformat: 'ISO8601Long', newformat: 'ISO8601Long'}
            }
            ,
            {
                name: 'action',
                index: 'action',
                align: 'middle',
                width: 50,

                formatter: function (cellvalue, options, rowObject) {
                    <s:if test="#request.context=='viewDialog'">
                    return "<A id='action_" + options.rowId + "' style='color:blue' title='" + 'View' + "'href='" + attachmentDownloadUrl + options.rowId + "'><s:text name="download"/></A>";
                    </s:if>
                    <s:else>
                    return "<A id='action_" + options.rowId + "' style='color:blue' title='" + 'View' + "'href='javascript:void(0)'><s:text name="delete"/></A>";
                    </s:else>
                }
            }

        ];

        var grid = $("#" + gridId, container).jqGrid({
            url: gridURL,
            postData: {
                prop: '',
                format: 'grid'
            },
            width: <s:if test="#request.context=='viewDialog'">850</s:if><s:else>850</s:else>,
            height: 100,
            datatype: 'local',
            mtype: 'post',
            pager: '#' + gridId + 'Pager',
            rowNum: 100,
            loadtext: 'Loading, please wait...',
            <s:if test="#request.context=='viewDialog'">
            caption: 'Attachments',
            </s:if>
            colNames: ['Name', 'Size', 'Upload time' , 'Action'],
            colModel: colModel,

            gridComplete: function () {
                //action
                $("a[id^='action_']", this).on('click', function () {
                    var _ref = this.id.split('_'), action = _ref[0], rowid = _ref[1];
//                    var rowData = grid.getRowData(rowid);
//                    rowData.id = rowid;
//                    console.log(rowData);
                    <s:if test="#request.context=='viewDialog'">

                    </s:if>
                    <s:else>
                    $.post('delete-attachment', {id: rowid}, function (json) {
                        console.log(json);
                        grid.delRowData(rowid);
                        return;
                    });
                    </s:else>
                });
            },
            afterCreate: function (grid) {
                grid.jqGrid('navGrid', '#' + gridId + 'Pager', {add: false, edit: false, del: false, search: false});
                grid.setGridParam({'datatype': 'json'});
                <s:if test="#request.context=='viewDialog'">
//                grid.setGridState('hidden');
                </s:if>
            }
        });

        grid.getGridParam('afterCreate')(grid);

    });

</script>

<table class="attachmentGrid_container">
    <tr>
        <td valign="top" align="left" class="attachmentGrid_parent">
            <table id="${param.gridId}">
                <tr>
                    <td></td>
                </tr>
            </table>
            <%--<div id="attachmentGridPager"/>--%>
        </td>
    </tr>
</table>